using System;
using System.Collections;
using System.Data.SqlClient;
using Microsoft.ApplicationBlocks.Data;

using LocalBoard.Domain;

namespace LocalBoard.Persistence.SqlAccessor
{
	/// <summary>
	/// Summary description for SqlPollItemAccessor.
	/// </summary>
	public class SqlPollItemAccessor : SqlDataAccessBase, IPollItemAccessor
	{
		public static readonly SqlPollItemAccessor Instance = new SqlPollItemAccessor();

		private SqlPollItemAccessor()
		{
		}
		#region IPollItemAccessor Members

		public System.Collections.ArrayList GetPollItemListByMessageId(int messageId)
		{
			using (SqlDataReader dataReader = SqlHelper.ExecuteReader(ConnectionString, "GetPollItemsByMessageId", messageId))
			{
				ArrayList pollItems = new ArrayList();
				while(dataReader.Read())
				{
					pollItems.Add(new PollItem(DataConverter.GetInteger(dataReader["Id"]), DataConverter.GetString(dataReader["Name"]), DataConverter.GetInteger(dataReader["Vote"])));
				}
				return pollItems;
			}
		}

		public int Insert(LocalBoard.Domain.PollItem pollItem, int messageId)
		{
			return Convert.ToInt32(SqlHelper.ExecuteScalar(ConnectionString, "InsertPollItem", pollItem.Name, messageId));
		}

		public void Delete(int id, int messageId)
		{
			if(this.GetVoterIdListByMessageId(messageId).Count == 0)
			{
				SqlHelper.ExecuteNonQuery(ConnectionString, "DeletePollItem", id);
			}
			else
				throw new Exception("You can not delete poll-items since a vote is already begun.");
		}

		public void PostPoll(int id, int messageId, int profileId)
		{
			SqlHelper.ExecuteNonQuery(ConnectionString, "InsertPoll", messageId, id, profileId);
		}

		public System.Collections.ArrayList GetVoterIdListByMessageId(int messageId)
		{
			ArrayList voters = new ArrayList();
			SqlDataReader dataReader = SqlHelper.ExecuteReader(ConnectionString, "GetVoteListByMessageId", messageId);

			while(dataReader.Read())
			{
				voters.Add(DataConverter.GetInteger(dataReader["Profile_Id"]));
			}
			dataReader.Close();
			return voters;
		}

		public void DeleteVotersForPollMessage(int messageId)
		{
			SqlHelper.ExecuteNonQuery(ConnectionString, "DeleteVotersByMessageId", messageId);
		}

		#endregion
	}
}
